const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const gameOverDiv = document.getElementById('gameOver');
const scoreSpan = document.getElementById('score');
const currentScoreSpan = document.getElementById('currentScore');
const colorSelection = document.getElementById('colorSelection');
const colorOptions = document.getElementById('colorOptions');
const startGameBtn = document.getElementById('startGameBtn');
const victoryDiv = document.getElementById('victory');
const victoryScoreSpan = document.getElementById('victoryScore');

let selectedColor;
let dx = 0;
let dy = 0;

// 预设最高分
const MAX_SCORE = 500;

// 颜色选项
const colors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF'];

// 生成颜色选项
colors.forEach(color => {
    const option = document.createElement('div');
    option.className = 'colorOption';
    option.style.backgroundColor = color;
    option.addEventListener('click', () => {
        selectedColor = color;
        startGameBtn.disabled = false;
        document.querySelectorAll('.colorOption').forEach(opt => {
            opt.style.borderColor = 'transparent';
        });
        option.style.borderColor = '#003366';
    });
    colorOptions.appendChild(option);
});

// 开始游戏按钮点击事件
startGameBtn.addEventListener('click', () => {
    colorSelection.style.display = 'none';
    initGame();
});

// 启用抗锯齿
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';

// 绘制鱼的函数
function drawFish(x, y, size, color, isPlayer = false) {
    // 保存当前绘图状态
    ctx.save();
    // 绘制阴影
    ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
    ctx.shadowBlur = 10;
    ctx.shadowOffsetX = 5;
    ctx.shadowOffsetY = 5;

    // 绘制鱼身体
    ctx.beginPath();
    const bodyWidth = size * 2;
    const bodyHeight = size;
    ctx.ellipse(x, y, bodyWidth / 2, bodyHeight / 2, 0, 0, Math.PI * 2);
    // 为鱼身体添加渐变
    const bodyGradient = ctx.createLinearGradient(x - bodyWidth / 2, y, x + bodyWidth / 2, y);
    bodyGradient.addColorStop(0, color);
    bodyGradient.addColorStop(1, darkenColor(color, 30));
    ctx.fillStyle = bodyGradient;
    ctx.fill();
    ctx.closePath();

    // 绘制鱼鳍
    ctx.beginPath();
    ctx.moveTo(x - bodyWidth / 2, y);
    ctx.quadraticCurveTo(x - bodyWidth * 0.7, y - bodyHeight * 0.4, x - bodyWidth * 0.6, y);
    ctx.quadraticCurveTo(x - bodyWidth * 0.7, y + bodyHeight * 0.4, x - bodyWidth / 2, y);
    const finGradient = ctx.createLinearGradient(x - bodyWidth / 2, y, x - bodyWidth * 0.6, y);
    finGradient.addColorStop(0, color);
    finGradient.addColorStop(1, darkenColor(color, 20));
    ctx.fillStyle = finGradient;
    ctx.fill();
    ctx.closePath();

    // 绘制鱼尾
    ctx.beginPath();
    ctx.moveTo(x + bodyWidth / 2, y);
    ctx.quadraticCurveTo(x + bodyWidth * 1.2, y - bodyHeight * 0.6, x + bodyWidth * 1.1, y);
    ctx.quadraticCurveTo(x + bodyWidth * 1.2, y + bodyHeight * 0.6, x + bodyWidth / 2, y);
    const tailGradient = ctx.createLinearGradient(x + bodyWidth / 2, y, x + bodyWidth * 1.1, y);
    tailGradient.addColorStop(0, color);
    tailGradient.addColorStop(1, darkenColor(color, 20));
    ctx.fillStyle = tailGradient;
    ctx.fill();
    ctx.closePath();

    // 绘制眼睛（仅玩家鱼）
    if (isPlayer) {
        ctx.beginPath();
        const eyeX = x + bodyWidth * 0.4;
        const eyeRadius = bodyHeight * 0.15;
        ctx.arc(eyeX, y, eyeRadius, 0, Math.PI * 2);
        ctx.fillStyle = 'white';
        ctx.fill();
        ctx.closePath();

        ctx.beginPath();
        ctx.arc(eyeX, y, eyeRadius * 0.4, 0, Math.PI * 2);
        ctx.fillStyle = 'black';
        ctx.fill();
        ctx.closePath();

        // 绘制眼睛高光
        ctx.beginPath();
        ctx.arc(eyeX + eyeRadius * 0.2, y - eyeRadius * 0.2, eyeRadius * 0.2, 0, Math.PI * 2);
        ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
        ctx.fill();
        ctx.closePath();
    }

    // 恢复之前保存的绘图状态
    ctx.restore();
}

// 辅助函数：加深颜色
function darkenColor(color, percent) {
    const hex = color.replace(/[^0-9A-F]/gi, '');
    const bigint = parseInt(hex, 16);
    let r = (bigint >> 16) & 255;
    let g = (bigint >> 8) & 255;
    let b = bigint & 255;

    r = Math.max(0, r - (255 * percent / 100));
    g = Math.max(0, g - (255 * percent / 100));
    b = Math.max(0, b - (255 * percent / 100));

    return `#${(r << 16 | g << 8 | b).toString(16).padStart(6, '0')}`;
}

// 玩家大鱼类
class PlayerFish {
    constructor() {
        this.x = canvas.width / 2;
        this.y = canvas.height / 2;
        this.size = 20;
        this.speed = 5;
        this.color = selectedColor;
        this.score = 0;
    }

    draw() {
        drawFish(this.x, this.y, this.size, this.color, true);
    }

    move(dx, dy) {
        this.x += dx * this.speed;
        this.y += dy * this.speed;

        // 边界限制
        this.x = Math.max(this.size, Math.min(this.x, canvas.width - this.size));
        this.y = Math.max(this.size / 2, Math.min(this.y, canvas.height - this.size / 2));
    }

    eat(fish) {
        const distance = Math.sqrt((this.x - fish.x) ** 2 + (this.y - fish.y) ** 2);
        if (distance < this.size + fish.size && this.size > fish.size) {
            this.size += Math.floor(fish.size * 0.1); // 取整
            this.score += Math.floor(fish.size); // 取整
            currentScoreSpan.textContent = this.score;
            // 检查是否达到最高分
            if (this.score >= MAX_SCORE) {
                victory();
            }
            return true;
        }
        return false;
    }
}

// 敌人类
class EnemyFish {
    constructor() {
        this.x = Math.random() * canvas.width;
        this.y = Math.random() * canvas.height;
        this.size = Math.floor(Math.random() * 30 + 10); // 取整
        this.speedX = (Math.random() - 0.5) * 3;
        this.speedY = (Math.random() - 0.5) * 3;
        let color;
        do {
            color = `#${Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0')}`;
        } while (color === selectedColor);
        this.color = color;
    }

    draw() {
        drawFish(this.x, this.y, this.size, this.color);
    }

    move() {
        this.x += this.speedX;
        this.y += this.speedY;

        // 边界反弹
        if (this.x - this.size < 0 || this.x + this.size > canvas.width) {
            this.speedX = -this.speedX;
        }
        if (this.y - this.size / 2 < 0 || this.y + this.size / 2 > canvas.height) {
            this.speedY = -this.speedY;
        }
    }
}

let player;
let enemies;

// 初始化游戏
function initGame() {
    player = new PlayerFish();
    enemies = [];
    for (let i = 0; i < 10; i++) {
        enemies.push(new EnemyFish());
    }
    // 键盘事件处理
    document.addEventListener('keydown', (e) => {
        if (e.key === 'ArrowLeft') dx = -1;
        if (e.key === 'ArrowRight') dx = 1;
        if (e.key === 'ArrowUp') dy = -1;
        if (e.key === 'ArrowDown') dy = 1;
    });

    document.addEventListener('keyup', (e) => {
        if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') dx = 0;
        if (e.key === 'ArrowUp' || e.key === 'ArrowDown') dy = 0;
    });

    gameLoop();
}

// 游戏结束函数
function gameOver() {
    gameOverDiv.style.display = 'block';
    scoreSpan.textContent = player.score;
}

// 胜利函数
function victory() {
    victoryDiv.style.display = 'block';
    victoryScoreSpan.textContent = player.score;
}

// 重新开始游戏函数
function restartGame() {
    gameOverDiv.style.display = 'none';
    victoryDiv.style.display = 'none';
    colorSelection.style.display = 'block';
    startGameBtn.disabled = true;
    document.querySelectorAll('.colorOption').forEach(opt => {
        opt.style.borderColor = 'transparent';
    });
    selectedColor = null;
}

// 游戏循环
function gameLoop() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    player.move(dx, dy);
    player.draw();

    enemies.forEach((enemy, index) => {
        enemy.move();
        enemy.draw();

        if (player.eat(enemy)) {
            enemies.splice(index, 1);
            enemies.push(new EnemyFish());
        } else if (enemy.size > player.size) {
            const distance = Math.sqrt((player.x - enemy.x) ** 2 + (player.y - enemy.y) ** 2);
            if (distance < player.size + enemy.size) {
                gameOver();
                return;
            }
        }
    });

    if (gameOverDiv.style.display !== 'block' && victoryDiv.style.display !== 'block') {
        requestAnimationFrame(gameLoop);
    }
}
